package com.zy.dingdong.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.alibaba.fastjson.JSON;
import com.zy.dingdong.R;
import com.zy.dingdong.util.OkHttpUtil;
import com.zy.dingdong.util.PictureUtil;
import com.zy.dingdong.util.RegexUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class CompleteUserInfoActivity extends BaseActivity {

    private static final String TAG = "HELLO";
    private ImageView returnBtn;
    private ImageView headingV;
    private EditText nameEdt;
    private EditText ageEdt;
    private EditText cityEdt;
    private Button completeInfoBtn;
    private String username;
    private PictureUtil pictureUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.complete_info);
        //全屏
        setFullScreen(CompleteUserInfoActivity.this);
        //绑定页面元素
        returnBtn = findViewById(R.id.back_register);
        headingV = findViewById(R.id.new_user_heading);
        nameEdt = findViewById(R.id.new_user_name);
        ageEdt = findViewById(R.id.new_user_age);
        cityEdt = findViewById(R.id.new_user_city);
        username = getIntent().getStringExtra("username");
        completeInfoBtn = findViewById(R.id.complete_user_info);

        pictureUtil = new PictureUtil(CompleteUserInfoActivity.this);

        //回退
        returnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CompleteUserInfoActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //更换图片
        headingV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] getPictureWays = new String[]{"相册", "相机"};
                AlertDialog dialog = new AlertDialog.Builder(CompleteUserInfoActivity.this)
                        .setItems(getPictureWays, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                switch (i) {
                                    case 0:
                                        pictureUtil.openPictureLib();
                                        break;
                                    case 1:
                                        pictureUtil.openCamera();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).create();
                dialog.show();
            }
        });
        //发送
        completeInfoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEdt.getText().toString();
                String age = ageEdt.getText().toString();
                String city = cityEdt.getText().toString();
                File imageFile = pictureUtil.getPictureFile();
                if (name.equals("") || age.equals("") || !RegexUtil.isNumber(age) || city.equals("") || imageFile == null){
                    Toast.makeText(CompleteUserInfoActivity.this, "请完善信息", Toast.LENGTH_SHORT).show();
                }else{
                    Map params=new HashMap();
                    params.put("name",name);
                    params.put("age",age);
                    params.put("city",city);
                    //保存头像
                    completeUserInfoRequest(params,imageFile);
                }
            }
        });
    }

    private void completeUserInfoRequest(final Map paramMap, final File file){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = SERVER_URL+"/user/"+username+"/completeUserInfo";
                    String jsonStr = OkHttpUtil.fileUpload(url,file,paramMap);
                    completeUserInfoResponse(jsonStr);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void completeUserInfoResponse(final String jsonStr){
        CompleteUserInfoActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map jsonMap = JSON.parseObject(jsonStr);
                final String message = (String) jsonMap.get("message");
                if (message.equals("success")){
                    //信息完善，跳转到登录页面
                    Toast.makeText(CompleteUserInfoActivity.this, "完成注册，请重新登录", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(CompleteUserInfoActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(CompleteUserInfoActivity.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "CompleteUserInfoActivity: 打开相册后的回调方法：" + data.toString());
        if (data.getData() == null){
            Toast.makeText(CompleteUserInfoActivity.this,"未选择图片",Toast.LENGTH_SHORT).show();
        }else {
            super.onActivityResult(requestCode, resultCode, data);
            pictureUtil.showPicture(requestCode, resultCode, data, CompleteUserInfoActivity.this, headingV);
        }
    }

    //请求权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //申请相机权限
        if (requestCode == PictureUtil.CAPTURE_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行拍照
                pictureUtil.doTake();
            } else{
               Toast.makeText(this,"你没有获得相机的权限",Toast.LENGTH_SHORT).show();
            }
        }
        //申请读取内存的权限
        else if (requestCode == PictureUtil.PICTURE_LIB_PERMISSION){
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //执行从相册选取图片
                pictureUtil.openAlbum();
            } else{
                Toast.makeText(this,"你没有获得访问相册的权限",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
